package com.weds.data_sync.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weds.data_sync.constant.ScriptServiceConstant;
import com.weds.data_sync.mapper.DataSyncRecordHistoryMapper;
import com.weds.data_sync.pojo.dto.RecordHistoryDTO;
import com.weds.data_sync.pojo.entity.DataSyncRecordHistoryDO;
import com.weds.data_sync.service.RecordHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @Description
 * @Author lihw
 * @Date 2024/1/15 11:25
 */
@Slf4j
@Service
public class RecordHistoryServiceImpl extends ServiceImpl<DataSyncRecordHistoryMapper, DataSyncRecordHistoryDO>
        implements RecordHistoryService {

    @Autowired
    private DataSyncRecordHistoryMapper recordHistoryMapper;

    /**
     * 增加执行计划分析记录的记录信息
     *
     * @param recordHistoryDTO
     * @return
     */
    @Override
    public Integer add(RecordHistoryDTO recordHistoryDTO) {
        DataSyncRecordHistoryDO recordHistoryDO = new DataSyncRecordHistoryDO();
        BeanUtils.copyProperties(recordHistoryDTO, recordHistoryDO);
        recordHistoryDO.setCtDate(LocalDateTime.now());
        recordHistoryDO.setLtDate(LocalDateTime.now());
        return recordHistoryMapper.insert(recordHistoryDO);
    }

    /**
     * 获取上次执行计划分析记录的记录信息
     *
     * @return
     */
    @Override
    public DataSyncRecordHistoryDO getPreviousAnalyseInfo() {
        DataSyncRecordHistoryDO recordHistoryDO = recordHistoryMapper.selectOne(new QueryWrapper<DataSyncRecordHistoryDO>()
                .eq("is_success", ScriptServiceConstant.CommonStatus.SUCCESS)
                .orderByDesc("id")
                .last("limit 1"));
        if (Objects.isNull(recordHistoryDO)) {
            return DataSyncRecordHistoryDO.builder()
                    .startRecordId("0")
                    .endRecordId("0")
                    .isSuccess(1)
                    .build();
        }
        return recordHistoryDO;
    }
}
